const App = getApp()
import download from '../../../utils/download.js'
import { SpecialModel } from '../../../models/special.js'
const ModeSpecial = new SpecialModel()
Page({
  data: {
    imageList: [],
    statusBarHeight: App.globalData.statusBarHeight,
    isTabbar: false,
    materialList: null,
    pageIndex: 1,
    pageSize: 10,
    specialId: '',
    hasNext: true,
    loading: false,
    specialInfo: {},
    shareCodeImg: '',
    download: {},
    material: []
  },
  onLoad: function (options) {
    console.log('onLoad material',options)
    // 好友链接或上个页面进入
    this.data.specialId = options.specialId // 专场id
    // 第一次加载
    this.loadMore(true)
  },
  //点击放大二维码
  preview(e) {
    const { item, index } = e.currentTarget.dataset
    var urlArr = []
    for (var i = 1; i < 9; i++) {
      urlArr.push(item[`img${i}`])
    }
    // 插入分享图
    urlArr.splice(4, 0, this.data.shareCodeImg)
    console.log(urlArr)
    wx.previewImage({
      current: urlArr[index], // 当前显示图片的http链接
      urls: urlArr // 需要预览的图片http链接列表
    })
  },
  //加载更多
  loadMore(reload) {
    if (reload) {
      this.setData({
        pageIndex: 1,
        hasNext: true
      })
    }
    if (this.data.loading || !this.data.hasNext) {
      return
    }
    const params = {
      pageIndex: this.data.pageIndex,
      pageSize: this.data.pageSize,
      specialId: this.data.specialId
    }
    // 不通过尺码搜索
    ModeSpecial.getSpecialMaterial(params)
      .then(res => {
        // 如果重新/第一次加载则清空 materialList
        if (reload) {
          this.setData({
            materialList: [],
            specialInfo: res.data.specialInfo
          })
        }
        const tempArray = this.data.materialList.concat(res.data.resourceList)
        this.setData({
          materialList: tempArray,
          hasNext: res.data.hasNext,
          loading: false
        })
        if (reload && this.data.materialList.length > 0) {
          // 生成二维码图
          this.renderCodeImg(res.data.specialInfo)
        }
        wx.stopPullDownRefresh()
      })
      .catch(err => {
        this.setData({
          loading: false
        })
      })
  },
  // 先生成二维码图
  renderCodeImg(shareInfo) {
    this.setData({
      showType: 'activity',
      shareData: {
        showWay: 'nobar',
        mode: 'path',
        shareTitle: shareInfo.specialName,
        mainImg: shareInfo.mainImg,
        shareImg: shareInfo.shareImg,
        startDate: shareInfo.startDate,
        endDate: shareInfo.endDate,
        specialCode: shareInfo.specialCode
      }
    })
  },
  // 获取生成二维码地址
  getCodeImgPath(event) {
    const { tempFilePath, errMsg } = event.detail
    var imgs = []
    if (errMsg === 'canvasdrawer:ok') {
      this.setData({
        shareCodeImg: tempFilePath
      })
      // 如果重复点击就直接显示
    } else if (errMsg === 'canvasdrawer:same params') {
      // 已经生成过了就直接拿
      if (this.data.shareCodeImg == '') {
        wx.showToast({ title: '生成二维码图片失败', icon: 'none' })
      }
    } else {
      wx.showToast({ title: '生成二维码图片失败', icon: 'none' })
    }
  },
  //点击一键发圈，第一步生成带二维码的分享图
  downloadImgs(event) {
    let that = this
    var imgs = []
    const item = event.currentTarget.dataset.item

    // 下载图片
    for (var i = 1; i < 9; i++) {
      imgs.push(item[`img${i}`])
    }
    // 下载所有图片
    download.downloadSaveFiles({
      urls: imgs,
      success: function(res) {
        const temps = res
        temps.push(that.data.shareCodeImg)
        // 保存到相册
        download
          .saveImageToAlbum(temps)
          .then(res => {
            wx.showToast({ title: '图片保存成功', icon: 'none' })
            setTimeout(() => {
              that.copyText(item.writer)
            }, 1000)
          })
          .catch(err => {
            console.log('失败')
            console.log(err)
          })
      },
      fail: function(e) {
        wx.hideLoading()
        console.info('下载失败')
      }
    })
  },
  // 保存文本
  copyText(text) {
    wx.setClipboardData({
      data: text,
      success: function(res) {
        wx.getClipboardData({
          success: function(res) {}
        })
      }
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.loadMore(true)
  },
  // 微信到底
  onReachBottom: function() {
    this.data.pageIndex = this.data.pageIndex + 1
    this.loadMore()
  }
})
